<?php

namespace common\core\controller;

use common\core\base\InvalidException;
use yii\base\Module;
use yii\filters\Cors;
use yii\helpers\ArrayHelper;
use yii\rest\Controller;
use yii\web\Response;

class PublicController extends Controller
{
    use \common\core\base\Controller;
    use InvalidException;

    public function __construct($id, Module $module, array $config = [])
    {
        parent::__construct($id, $module, $config);
    }

    public function behaviors()
    {
        header("Access-Control-Allow-Origin: *");
        $behaviors = parent::behaviors();
        $behaviors['contentNegotiator']['formats'] = ['application/json' => Response::FORMAT_JSON,];
        $behaviors['rateLimiter']['enableRateLimitHeaders'] = true;
        $behaviors = ArrayHelper::merge($behaviors, [
            'jsonp' => [
                'class' => Cors::class,
                'cors'  => [
                    'Origin'                         => ['*'],
                    'Access-Control-Request-Headers' => ['*'],
                    'Access-Control-Request-Method'  => ['GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS'],
                ],
            ],
        ]);

        return $behaviors;
    }

    public function beforeAction($action)
    {
        $lang =  \Yii::$app->request->headers->get('x-api-language');
        \Yii::$app->language  = $lang ? $lang : 'en-US';
        $row = parent::beforeAction($action);
//        \Yii::$app->language = 'zh-TW';
//        var_dump(\Yii::t('app','signUp'));
//        \Yii::$app->language = 'en-Us';
//        var_dump(\Yii::t('app','signUp'));
        return $row;
    }

    final public function createAction($id)
    {
        if ($id === '') {
            $id = $this->defaultAction;
        }

        $actionMap = $this->actions();
        if (isset($actionMap[$id])) {
            return \Yii::createObject($actionMap[$id], [$id, $this]);
        }

        return null;
    }
}
